var koa = require('koa');
var app = koa();
var config = require('./config/config.js');
var path = require('path');
var debug = require('debug')('app_http');

// ---logger
app.use(function*(next) {
    var start = new Date();
    yield next;
    var ms = new Date() - start;
    debug('%s %s - %s', this.method, this.url, ms);
});


// ---session
var session = require('koa-session');
// session.maxAge = 24 * 3600 * 1000; // 1 day
session.maxAge = 60 * 1000; // 1 min
app.keys = ['koa-session'];
app.use(session(app));
// app.use(function*(next) {
//     var n = this.session.views || 0;
//     this.session.views = ++n;
//     debug('session.views=%s', this.session.views);
//     yield next;
// });


// ---enable cross domain
app.use(function*(next) {
    this.set("Access-Control-Allow-Origin", "*");
    this.set("Access-Control-Allow-Methods", "*");
    this.set("Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept");
    if (this.method === 'OPTIONS') {
        this.body = "Access-Control-Allow-Origin";
    } else {
        yield next;
    }
});


// ---body parser
var bodyParser = require('koa-body-parser');
app.use(bodyParser());


// ---static folder
var serve = require('koa-static');
var staticPath = path.join(__dirname, '../public');
app.use(serve(staticPath));


// ---router TODO 
debug('----load router-----');

app.use(require('./api/all.js')); // all
// app.use(require('./api/v1/testv1.js')); // test
app.use(require('./api/v1/user.js')); //
app.use(require('./api/v1/thread.js')); //
app.use(require('./api/v1/permission.js')); //
app.use(require('./api/v1/vendor.js')); //
app.use(require('./api/v1/role.js')); //
app.use(require('./api/v1/orgnization.js')); //
app.use(require('./api/v1/comment.js')); //

// debug('----load router done-----');


// ---404
app.use(function*() {
    this.status = 404;
    this.body = '~~404 not found~~';
});


// --- start
app.listen(config.http.port, function() {
    console.log('server listen at ' + config.http.port);
});